using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.TroubleCommand;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.TroubleCommandHandlers
{
    /// <summary>
    /// 聊天历史查询命令处理器
    /// </summary>
    public class GetChatHistoryCommandHandler : IRequestHandler<GetChatHistoryCommand, APIResult<List<ChatListItem>>>
    {
        private readonly SqlSugarContext sugar;

        public GetChatHistoryCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }

        public async Task<APIResult<List<ChatListItem>>> Handle(GetChatHistoryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ChatListItem>> result = new APIResult<List<ChatListItem>>();
            try
            {
                // 查询医生和患者之间的聊天记录
                var list = sugar.db.Queryable<ChatListItem>()
                    .Where(x => !x.IsDel)
                    .Where(x => 
                        // 医生发给患者的消息
                        (x.Sender == request.DoctorName && x.ContactName == request.PatientId) ||
                        // 患者发给医生的消息
                        (x.Sender == request.PatientId && x.ContactName == request.DoctorName))
                    .OrderBy(x => x.ChatTime)
                    .Skip(request.Skip)
                    .Take(request.Limit)
                    .ToList();

                // 将未读消息标记为已读（患者发给医生的且未读的消息）
                var unreadMessages = list.Where(x => x.Sender == request.PatientId && 
                                                x.ContactName == request.DoctorName && 
                                                x.HasRedDot).ToList();
                
                if (unreadMessages.Any())
                {
                    foreach (var msg in unreadMessages)
                    {
                        msg.HasRedDot = false;
                    }
                    
                    await sugar.db.Updateable(unreadMessages)
                        .UpdateColumns(x => new { x.HasRedDot })
                        .ExecuteCommandAsync();
                }

                result.data = list;
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询聊天历史时发生异常: {ex.Message}");
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
            }
            return result;
        }
    }
} 